// var qqMap = require('./qqmap-wx-jssdk.min.js');
var app = getApp();
// var gettokenurl = app.data.url +'api/api/getQiniuToken';
//循环数组和json对象
function each(data, func) {
  if(Array.isArray(data)){
    for (var a = 0; a < data.length; a++) {
      func(a, data[a])
    }
  }else{
    var r = '';
    for(r in data){
      func(r,data[r]);
    }
  }
}
//添加数据
function addArray(array=[],arrays=[]){
  this.each(arrays,function(i,v){
    array.push(v);
  })
  return array;
}
//通过年月获取数组
function strToDays(year,month){
  var number = (new Date(year,month,0)).getDate();
  var days = [];
  var str = '';
  var times = 0;
  var duixiang = [];
  var as = '';
  var newdata = new Date();
  // var newdata = 
  for(var a=1;a<=number;a++){
    str = year + '-' + month + '-' + a;
    times = Date.parse(str);
    if (year == newdata.getFullYear() && parseInt(month)==(newdata.getMonth()+1)&&a == newdata.getDate()){
      duixiang.push({
        year: year,
        month: month,
        day: a,
        week: (new Date(times)).getDay(),
        // times: times,
        today: true
      });
    }else{
      duixiang.push({
        year: year,
        month: month,
        day: a,
        week: (new Date(times)).getDay(),
        // times: times,
        today: false
      });
    }
  }
  return duixiang;
}
//网络请求
function request(url,data,func,msg=null){
  if(msg){
    wx.showLoading({
      title: msg,
    })
  }else{
    wx.showLoading({
      title: '加载中',
    })
  }
  wx.request({
    url: url,
    data: data,
    header: {},
    method: 'POST',
    dataType: 'json',
    responseType: 'text',
    success: function(res) {
      wx.hideLoading()
      if(func){
        func(res);
      }
    },
    fail: function(res) {
      wx.hideLoading()
    },
    complete: function(res) {
    },
  })
}
function qinqiu(url, data, func, msg = null,error){
  if (msg) {
    wx.showLoading({
      title: msg,
    })
  } else {
    wx.showLoading({
      title: '加载中',
    })
  }
  wx.request({
    url: url,
    data: data,
    header: {},
    method: 'POST',
    dataType: 'json',
    responseType: 'text',
    success: function (res) {
      wx.hideLoading()
      var data = res.data;
      console.log(res);
      if(data.code==200){
        if (func) {
          func(data.data);
        }
      }else{
        wx.showToast({
          title: data.msg,
          icon:'none'
        })
      }
    },
    fail: function (res) {
      wx.hideLoading()
      if(error){
        error(res);
      }
     },
    complete: function (res) {
    },
  })
}
//通过年月日返回字符串
function timeToDays(year, month,day){
  var str = year+'-'+month+'-'+day;
  str = Date.parse(str);
  str = new Date(str).getDay();
  return str;
}
//倒计时
function TimeDown(times,func){
  var time = times;
  var funcs = function(){
    if(time>0){
      time = time-1
      if(func){
        func(time);
      }
    }else{
      clearInterval(buts);
    }
  }
  var buts = setInterval(funcs,1000);
}
//判断是否是img
function isImg(array){
  var arr = ['jpg','jpeg','png','gif'];
  var end = '';
  var bools = true;
  var ones = '';
  var that = this;
  this.each(array,function(i,v){
    ones = false;
    end = v.split('.');
    end = end[end.length-1];
    that.each(arr,function(is,vs){
      if(vs==end){
        ones = true;
      }
    })
    if(!ones){
      bools = false;
    }
  })
  return bools;
}

//获取当前的地址的详情
// function getLocation(func){
//   var data = [];
//   wx.getLocation({
//     type: 'wgs84',
//     success: function (res) {
//       // console.log(res)
//       var latitude = res.latitude;
//       var longitude = res.longitude;
//       var app = getApp();
//       var test = new qqMap({
//         key: app.data.qqmapkey
//       });
//       test.reverseGeocoder({
//         location: {
//           latitude: latitude,
//           longitude: longitude
//         },
//         success: function (ress) {
//           // console.log(ress);
//           var result = ress.result;
//           // console.log(result);
//           var data = { address: result.address, guo: result.address_component.nation, shen: result.address_component.province, xian: result.address_component.district, shi: result.address_component.city };
//           if (func) {
//             func(data)
//           } else {
//             console.log(data);
//           }
//         }
//       })
//     },
//   })
// }
//获取当前的时间数组
function timeToarray(time=null){
  if(!time){
    time = new Date();
  }
  var year = time.getFullYear();
  var month = time.getMonth()+1;
  if(month<10){
    month = '0'+month;
  }
  var day   = time.getDate();
  if(day<10){
    day = '0'+day;
  }
  return {year:year,month:month,day:day};
}
//验证数据
function yanzhen(data, array) {
  var a = 0;
  var str = false;
  this.each(array, function (i, v) {
    if ((!data[i] || data[i] == '') && data[i] !== 0) {
      a = 1;
      str = v;
    }
  })
  return str;
}
//检测更新
function toUpdata(func){
  wx.getUpdateManager().onCheckForUpdate(function(res){
    console.log("是否有新版本：" + res.hasUpdate);
    if(func){
      func(res.hasUpdate);
    }
    if(res.hasUpdate){
      wx.showToast({
        title: '系统有更新',
        icon:'none'
      })
    }
    wx.getUpdateManager().onUpdateReady(function(){
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，单击确定重启应用',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            console.log('已下载好了')
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            wx.getUpdateManager().applyUpdate();
          }
        }
      })
    })
  })
}
//截取数组
function jiequ(array,s){
  var array1 = [];
  var array2 = [];
  if(Array.isArray(array)){
    for(var a = 0;a<array.length;a++){
      // console.log(s);
      if(a%s==0){
        array1 = [];
      }
      array1.push(array[a]);
      // console.log(array1);
      if (a % s == (s - 1) && a == (array.length - 1)){
        // console.log(a);
        array2.push(array1);
      } else if (a == (array.length - 1)){
        array2.push(array1);
      } else if(a % s == s-1){
        array2.push(array1);
      }
    }
  }else{
    array2 = false;
  }
  return array2;
}


//获取数据的经纬度
function strToJingWei(str,func){
  var app = getApp();
  var jingwei = new qqMap({
    key:app.data.qqmapkey
  });
  jingwei.geocoder({
    address:str,
    success:function(res){
        if(res.status==0){
          var lat = res.result.location.lat;
          var lng = res.result.location.lng;
          var data = { latitude: lat, longitude :lng}
          func(data);
        }else{
          console.log('获取失败');
        }
    }
  })
}
//上传文件到七牛云
function upfile(src = [], func, gettokenurl, uptype, jindu, getidurl, quanbu, change_name = true, name = []){
  var that  = this;
  var key = [];
  if(src.length==0){
    func([]);
  }
  if (!uptype){
    uptype = 'SCN';
  }
  var uploadURL = '';
  if (!uptype){
    uploadURL = 'https://upload.qiniup.com';
  }else{
    switch (uptype) {
      case 'ECN': uploadURL = 'https://up.qiniup.com'; break;
      case 'NCN': uploadURL = 'https://up-z1.qiniup.com'; break;
      case 'SCN': uploadURL = 'https://up-z2.qiniup.com'; break;
      case 'NA': uploadURL = 'https://up-na0.qiniup.com'; break;
      case 'ASG': uploadURL = 'https://up-as0.qiniup.com'; break;
      default: console.error('please make the region is with one of [ECN, SCN, NCN, NA, ASG]');
    }
  }
  var user = wx.getStorageSync('user');
  wx.request({
    url: gettokenurl,
    method:'post',
    data:{token:user.token},
    success:function(res){
      // console.log(res);
      // return;
      var data = res.data;
      if(data.code==200){
        if(src.length>0){
          var uptoken = data.data.token;
          var urls = data.data.url;
          var names = [];
          var times = '';
          var newname = '';
          var number = 0;
          for (var a = 0; a < src.length; a++) {
            if (change_name || name.length < 1) {
              times = (new Date()).getTime() + Math.floor(Math.random() * 10000)+a;
              newname = src[a].split('.').pop();
              newname = times + '.' + newname;
            } else {
              if (name[a]) {
                newname = name[a];
              } else {
                newname = name[0];
              }
            }
            key.push(newname);
            var uploadTask  = wx.uploadFile({
              url: uploadURL,
              filePath: src[a],
              name: 'file',
              formData: { token: uptoken, key: newname },
              success: function (res) {
                // console.log(res);
                var dat = JSON.parse(res.data);
                // console.log(dat);
                if (res.statusCode == 200) {
                  // console.log(newname);
                  names.push(urls+'/'+dat.key);
                  number++;
                  if (number == src.length){
                    // console.log('上传完成')
                    if(func){
                      func(names, key);
                    }
                    if (getidurl,quanbu){
                      wx.request({
                        url: getidurl,
                        data: { name: key},
                        method:"POST",
                        success:function(news){
                          quanbu(news);
                        }
                      })
                    }
                  }
                  // console.log('上传成功')
                } else {
                  console.log('上传失败');
                }
              },fail:function(res){
                console.log(res)
              }
            })
            uploadTask.onProgressUpdate(function(e){
              if (jindu){
                jindu(e);
              }
            })
          }
        }else{
          return false;
        }
      }else{
        wx.showToast({
          title: '获取上传凭证失败',
          icon:'none'
        })
      }
    }
  })
}
//
function showToUp(type, count, quanbu, jindu, func, gettokenurl, getidurl, uptype, change_name = true, name = []){
  if(!type){
    type = 'img';
  }
  if(!count){
    count = 1;
  }
  if(!gettokenurl){
    gettokenurl = app.data.url +'sheyingjia/Xuploas1/gettoken';
  }
  if (!getidurl){
    getidurl = app.data.url + 'sheyingjia/Xuploas1/addenclosure';
  }
  if(type=='img'){
    wx.chooseImage({
      count: count,
      success: function(res) {
        console.log(res);
        var tempFilePaths = res.tempFilePaths;
        upfile(tempFilePaths, func, gettokenurl, uptype, jindu, getidurl, quanbu, change_name, name);
      },
    })
  }
}
/**
 * 获取浮点数
 */
function getFloat(str){
  str = parseInt(parseFloat(str)*100)/100;
  return str;
}
function strTofloat(str){
  var array = str.split('');
  var newarray = [];
  each(array,function(i,v){
    if(i==0&&v=='0'){

    }else{
      newarray.push(v);
    }
  })
  return newarray.join('');
}
module.exports={
  each: each,
  // getLocation: getLocation,
  strToJingWei: strToJingWei,
  timeToarray: timeToarray,
  upfile: upfile,
  yanzhen: yanzhen,
  jiequ: jiequ,
  toUpdata: toUpdata,
  addArray: addArray,
  strToDays: strToDays,
  timeToDays: timeToDays,
  TimeDown: TimeDown,
  request: request,
  isImg: isImg,
  showToUp: showToUp,
  qinqiu: qinqiu,
  getFloat: getFloat,
  strTofloat: strTofloat
}